import React from 'react';
import menuRoute from 'routes/menuRoute';
import ViewHistory from "containers/loan-billing/template/view-history";
import {dealCache, deepFullCopy, messages, queryCurrencyPrecision} from 'share/common';
import { Form, Icon, Badge, Spin, Row, Col, Modal, message, Popover } from 'antd';
import moment from 'moment';
import SearchArea from 'components/search-area';
import loanAndRefundService from 'containers/financial-management/loan-and-refund/loan-and-refund.service';
import 'styles/financial-management/loan-and-refund/overall-sub-list.scss';
import {connect} from "react-redux";
import configureStore from "stores";
import {setOverallSubList} from "actions/cache";
import repaymentContent from "containers/loan-billing/template/repayment-content";
import SlideFrame from 'components/slide-frame';
import borrowService from "../../loan-billing/borrow-and-return.service";
import ResizeTable from 'components/resize-table'
import viewLine from "containers/loan-billing/template/view-line";
import refundContent from 'containers/loan-billing/template/refund-content';

let cacheSearchData={};

class OverallSubList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      loanInfo: {},
      searchForm: [
        {type: 'items', id: 'dataRange', items: [
          {type: 'date', id: 'startDateTime', label: messages('financial-management.key247'/*借款提交日期从*/)},
          {type: 'date', id: 'endDateTime', label: messages('financial-management.key248'/*借款提交日期至*/)}
        ]},
        {type: 'input', id: 'businessCodeL', label: messages('financial-management.key246'/*借款单号*/)},
        {type: 'input', id: 'employeeKey', label: messages('financial-management.key579')/*申请人/代理人*/,placeholder: messages('financial-management.key579')/*申请人/代理人*/}
      ],
      searchParams: {},
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: 48, render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('financial-management.key267'/*借款日期*/), dataIndex: 'createdDate', width: 120, render: value => moment(value).format('YYYY-MM-DD')},
        { title: messages('financial-management.key246'/*借款单号*/), dataIndex: 'businessCode',
          render: (value, record) => <a onClick={e => this.handleRowClick(e, record)}>{value}</a> },
        {title: messages('financial-management.key579')/*申请人/代理人*/, dataIndex: 'applicantName', render: (value,record) => record.submittedBy === record.applicantOid ? value : `${value}/${record.submittedName}`},
        { title: messages('financial-management.key669')/*借款类型*/, dataIndex: 'loanTypeName' },
        { title: messages('financial-management.key894')/*事由*/, dataIndex: 'remark', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover> },
        {title: messages('common.currency'), dataIndex: 'currencyCode', width: '10%'},
        {title: messages('financial-management.key250'/*借款总额*/), dataIndex: 'amount',align:'right', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('financial-management.key251'/*待还款总额*/), dataIndex: 'stayWriteOffAmount', align:'right',render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('common.column.status'), dataIndex: 'status', width: '10%',render: value => value === '1006' ? <Badge text={messages('loan-billing.key8')/*还款中*/} status="success"/> :
            (value === '1007' ? <Badge text={messages('loan-billing.key9')/*已还款*/} status="success"/> : <Badge text={messages('financial-management.key409')/*已付款*/} status="success"/>)},
        {title: messages('financial-management.key254')/*操作*/, dataIndex: 'operator', render: (value, record) => <div>
            {
              record.stayWriteOffAmount > 0 && !record.creditLocked &&
              this.checkFunctionProfiles(['finance.cash.repaymemt.disabled'], [[false, undefined]])
              && <div>
                <a onClick={e => this.handleRepayment(e,record)}>{messages('loan-billing.key42')/*新建还款*/}</a>
              </div>
            }
            <div>
              <a onClick={e => this.handleViewHistory(e,record)}>{messages('loan-billing.key121')/*还款历史*/}</a>
            </div>
          </div>
        }
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      loanAndRefundList: menuRoute.getRouteItem('loan-and-refund','key'), //列表页
      loanRefundDetail: menuRoute.getRouteItem('loan-refund-detail','key'), //申请单详情页
      info: {},
      repayFrame: false,
      allLoading: false,
      transactionList: [],
      modalShow: false,
      editTransaction: {},
      rowSelection: {
        type: 'radio',
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem
      },
      transactionColumns: [
        {title: messages('financial-management.key663')/*交易日期*/, dataIndex: 'createdDate', render: value =>  moment(value).format('YYYY-MM-DD')},
        {title: messages('financial-management.key664')/*付款流水号*/, dataIndex: 'transactionDetailCode'},
        {title: messages('financial-management.key405')/*币种*/, dataIndex: 'currencyCode'},
        {title: messages('financial-management.key279')/*总金额*/, dataIndex: 'amount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('financial-management.key665')/*可还款金额*/, dataIndex: 'repaymentValue', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))}
      ],
      viewFrame: false,
      viewId: '',
      historyId: '',
      historyModal: false,
      refundParams: '',
      refundFrame: false
    }
  }

  componentWillMount() {
    this.getEmployeeLoanInfo();
    this.getCache();
  }

  handleViewHistory = (e,record) => {
    e.stopPropagation();
    this.setState({ historyId: record.id }, () => this.setState({ historyModal: true }));
  };

  handleRepayment = (e,record) => {
    e.stopPropagation();
    this.setState({allLoading: true});
    borrowService.getTransactionList(record.id).then(res => {
      if(res.data.length === 0){
        message.error(messages('financial-management.key666')/*该借款行无支付流水*/);
        this.setState({allLoading: false});
        return -1;
      }
      let temp = {
        allLoading: false,
        transactionList: res.data
      };
      res.data.length > 1 ? (temp.modalShow = true) : (temp.repayFrame = true);
      let infoRecord = deepFullCopy(record);
      infoRecord.stayWriteOffAmount = res.data[0].repaymentValue;
      infoRecord.transactionDetailId = res.data[0].transactionDetailId;
      infoRecord.transactionDetailCode = res.data[0].transactionDetailCode;
      this.setState({info: infoRecord},() => {
        this.setState(temp);
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({allLoading: false});
    })
  };

  setCache (result) {
    let {page} = this.state;
    result.page = page;
    cacheSearchData=result;
  }

  getCache () {
    let result = this.props.overallSubList;
    if(result&&JSON.stringify(result) !== "{}"){
      cacheSearchData=result;
      this.dealCache(result);
    }
    else{
      this.getList()
    }
  }

  dealCache (result) {
    let {searchForm, page} = this.state;
    let defaultSearchForm = deepFullCopy(searchForm);
    if (result) {
      page = result.page;
      dealCache(defaultSearchForm, result);
      this.setState({ searchForm: defaultSearchForm, page}, () => {
        this.onSearch(result);
        configureStore.store.dispatch(setOverallSubList(null));
      })
    }
  }

  getEmployeeLoanInfo = () => {
    let payeeId = this.props.loanParams.payeeId;
    let currencyCode = this.props.loanParams.currencyCode;
    loanAndRefundService.getLoanInfoByEmployeeId(payeeId,currencyCode).then(res => {
      this.setState({loanInfo: res.data || {}})
    })
  };

  getList = () => {
    const { page, pageSize, searchParams, pagination } = this.state;
    this.setState({ loading: true });
    let payeeId = this.props.loanParams.payeeId;
    let currencyCode = this.props.loanParams.currencyCode;
    let companyID = this.props.loanParams.companyID;
    searchParams.payeeId = payeeId;
    searchParams.currencyCode = currencyCode;
    searchParams.companyID = companyID;
    loanAndRefundService.getLoanListByEmployeeId(page, pageSize, searchParams).then(res => {
      pagination.total = Number(res.headers['x-total-count']) || 0;
      pagination.current = page + 1;
      pagination.onChange = this.onChangePaper;
      this.setState({
        loading: false,
        data: res.data,
        pagination
      })
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      },() => {
        this.getList()
      })
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
    }
  };

  //搜索
  onSearch = (value) => {
    this.setCache({...value});
    value.startDateTime && (value.startDateTime = moment(value.startDateTime).format('YYYY-MM-DD 00:00:00'));
    value.endDateTime && (value.endDateTime = moment(value.endDateTime).format('YYYY-MM-DD 23:59:59'));
    this.setState({ searchParams: value }, () => {
      this.getList()
    })
  };

  //清空
  onClear = () => {
    this.setState({ searchParams: {} }, () => {
      this.getList()
    })
  };

  //返回
  handleBack = () => {
    this.context.router.push(this.state.loanAndRefundList.url)
  };

  handleRowClick = (e, record) => {
    e.stopPropagation();
    configureStore.store.dispatch(setOverallSubList(cacheSearchData));
    this.context.router.push(this.state.loanRefundDetail.url.replace(':formOID', record.formOid).replace(':loanBillOID', record.loanBillOid).replace(':backType','history'));
  };

  handleClose = value => {
    this.setState({repayFrame: false, info: {}},() => {
      if(typeof value === 'boolean' && value){
        this.getList();
      }
    });
  };

  turnToRepayment = () => {
    const { editTransaction, info } = this.state;
    if(Object.keys(editTransaction).length === 0){
      message.error(messages('financial-management.key667')/*请选择支付流水号*/);
      return -1;
    }
    info.stayWriteOffAmount = editTransaction.repaymentValue;
    info.transactionDetailId = editTransaction.transactionDetailId;
    info.transactionDetailCode = editTransaction.transactionDetailCode;
    this.setState({modalShow: false, info}, () => {
      this.setState({repayFrame: true});
    })
  };

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    if(selected){
      this.setState({editTransaction: record});
    }
  };

  handleView = record => {
    this.setState({ viewFrame: true, viewId: record.id });
  };

  handleViewRefund = item => {
    if (item.type === 2 || item.type === 3) {
      this.context.router.push(menuRoute.getRouteItem('expense-report-detail').url.replace(':expenseReportOID', record.expenseReportOid).replace(':pageFrom','my'));
    } else {
      this.setState({ refundFrame: true, refundParams: item.repaymentOid, historyModal: false });
    }
  };

  render() {
    const { loading, loanInfo, searchForm, columns, data, pagination, info, repayFrame, allLoading, modalShow,
      transactionList, rowSelection, transactionColumns, viewFrame, viewId, historyModal, historyId, refundFrame,
      refundParams } = this.state;
    return (
      <Spin  spinning={allLoading}>
      <div className="overall-sub-list">
        <div className="employee-loan-info">
          <div>
            {loanInfo.payeeName}
            {loanInfo.payeeType === 1002 &&
              <span className="employee-info">{loanInfo.employeeId} - {loanInfo.roleName}{loanInfo.roleName ? ' - ' : ''}{loanInfo.departmentPath}</span>
            }
            {loanInfo.payeeType === 1001 &&
              <span className="employee-info">{loanInfo.payeeCode} - {loanInfo.supplierType ? loanInfo.supplierType : '-'}</span>
            }
          </div>
          <div>
            <span className="loan-amount"> {messages('financial-management.key576')/*借款公司*/}：
              {loanInfo.companyName}
            </span>
            <span className="loan-amount">
              {messages('financial-management.key250'/*借款总额*/)}：
              {loanInfo.currencyCode} {this.filterMoney(loanInfo.loanSum,queryCurrencyPrecision(loanInfo.currencyCode),true)}
            </span>
            {messages('financial-management.key251'/*待还款总额*/)}：
            <span className={loanInfo.stayWriteOffSum === 0 ? 'color-999' : 'color-red'}>
              {loanInfo.currencyCode} {this.filterMoney(loanInfo.stayWriteOffSum,queryCurrencyPrecision(loanInfo.currencyCode),true)}
            </span>
          </div>
        </div>
        <SearchArea searchForm={searchForm}
                    isReturnLabel={true}
                    submitHandle={this.onSearch}
                    clearHandle={this.onClear}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total || 0})/*共 total 条数据*/}</div>
        </div>
        <ResizeTable
          rowKey={(record, index) => index}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onRow={record => ({onClick: () => this.handleView(record)})}
          size="middle"
          bordered
        />
        <a onClick={this.handleBack}><Icon type="rollback" className="back-icon"/>{messages('common.back')}</a>
        <SlideFrame show={repayFrame}
                    title={messages('loan-billing.key42')/*新建还款*/}
                    key='repaymentLoan'
                    content={repaymentContent}
                    params={{info, repayFrame, loanRefund: true}}
                    onClose={this.handleClose}
                    afterClose={this.handleClose}/>
        <Modal visible={modalShow}
               title={messages('financial-management.key668')/*选择支付流水*/}
               onOk={this.turnToRepayment}
               onCancel={() => {
                 this.setState({
                   modalShow: false,
                   editTransaction: {}
                 })
               }}>
          <Row>
            <Col span={11}> {messages('financial-management.key246')/*借款单号*/}：{transactionList[0] ? transactionList[0].businessCode : '-'}
            </Col>
            <Col span={12} offset={1}> {messages('financial-management.key582')/*借款行号*/}：{transactionList[0] ? transactionList[0].sequence : '-'}
            </Col>
          </Row>
          <Row>
            <Col span={11}> {messages('financial-management.key575')/*收款人*/}：{transactionList[0] ? transactionList[0].payeeName : '-'}
            </Col>
            <Col span={12} offset={1}> {messages('financial-management.key669')/*借款类型*/}：{transactionList[0] ? transactionList[0].loanTypeName : '-'}
            </Col>
          </Row>
          <ResizeTable
            dataSource={transactionList}
            rowSelection={rowSelection}
            rowKey="transactionDetailId"
            columns={transactionColumns}
            bordered
          />
        </Modal>
        <SlideFrame
          show={viewFrame}
          title={messages('loan-billing.key118')/*查看借款计划*/}
          key='viewLine'
          content={viewLine}
          params={{
            viewFrame,
            viewId
          }}
          onClose={() => {this.setState({viewFrame: false})}}
          afterClose={() => {this.setState({viewFrame: false})}}
        />
        <ViewHistory
          visible={historyModal}
          id={historyId}
          handleViewRefund={this.handleViewRefund}
          close={() => this.setState({historyModal: false})}
        />
        <SlideFrame
          show={refundFrame}
          title={messages('loan-billing.key89')/*还款详情*/}
          key='refund'
          content={refundContent}
          params={{
            refundFrame,
            refundParams,
            location: this.props.location
          }}
          onClose={() => this.setState({refundFrame: false})}
          afterClose={() => this.setState({refundFrame: false})}
        />
      </div>
      </Spin>
    )
  }
}

OverallSubList.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    overallSubList: state.cache.overallSubList,
    loanParams: state.billing.loanParams
  }
}
const WrappedOverallSubList = Form.create()(OverallSubList);

export default connect(mapStateToProps)(WrappedOverallSubList);
